<?php

namespace App\Models;

use App\Models\BaseModel;

/**
 * 角色模型
 */
class Role extends BaseModel
{
    protected $table = 'roles';

    const SUPER_ROLE_ID = 1;// 超管角色id

    /**
     * 状态：禁用
     */
    const STATUS_DISABLED = 0;

    /**
     * 状态：启用
     */
    const STATUS_ENABLED = 1;

    /**
     * 获取表字段
     * @return array
     */
    protected function columns(): array
    {
        return [
            'id',
            'name',
            'description',
            'status',
            'created_at',
            'updated_at',
            'deleted_at'
        ];
    }

    protected function buildQuery(array $params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::buildQuery($params);
        
        if (!empty($params['keyword'])) {
            $query->where('name', 'like', '%' . $params['keyword'] . '%');
        }
        if (!empty($params['start_time'])) {
            $startTime = strtotime($params['start_time']);
            $query->where('created_at', '>=', $startTime);
        }
        if (!empty($params['end_time'])) {
            $endTime = strtotime($params['end_time']) + 86400 - 1;
            $query->where('created_at', '<=', $endTime);
        }
        return $query;
    }

    /**
     * 关联角色权限
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function rolePermissions()
    {
        return $this->hasMany(RolePermission::class, 'role_id', 'id');
    }

    /**
     * 关联权限（通过角色权限关联表）
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'role_permissions', 'role_id', 'permission_id');
    }
}
